import markdownit from "markdown-it";
import mk from "@xtthaop/markdown-it-katex";
import hljs from "highlight.js";
import "./MarkdownViewer.scss";
import "katex/dist/katex.css";
import { useEffect, useState } from "react";

let noteTimeStampArr = [];
let noteTimeStampElems;

const animateScrollTo = (element, to, duration) => {
  const start = element.scrollTop;
  const change = to - start;
  const startDate = +new Date();
  // t = current time
  // b = start value
  // c = change in value
  // d = duration
  const easeInOutQuad = (t, b, c, d) => {
    let t2 = t;
    t2 /= d / 2;
    if (t2 < 1) return (c / 2) * t2 * t2 + b;
    t2 -= 1;
    return (-c / 2) * (t2 * (t2 - 2) - 1) + b;
  };
  const animateScroll = () => {
    const currentDate = +new Date();
    const currentTime = currentDate - startDate;
    element.scrollTop = parseInt(
      easeInOutQuad(currentTime, start, change, duration),
      10,
    );
    if (currentTime < duration) {
      requestAnimationFrame(animateScroll);
    } else {
      element.scrollTop = to;
    }
  };
  animateScroll();
};

const MarkdownViewer = ({ content, videoTimeStamp, containerRef }) => {
  // const [timeStamp, setTimeStamp] = useState();
  const [HTMLContent, setHTMLContent] = useState();
  useEffect(() => {
    noteTimeStampArr = [];
    // 创建markdown实例
    const md = markdownit({
      highlight: function (str, lang) {
        // 获得语法高亮
        if (lang && hljs.getLanguage(lang)) {
          try {
            return (
              '<pre><code class="hljs">' +
              hljs.highlight(str, { language: lang, ignoreIllegals: true })
                .value +
              "</code></pre>"
            );
          } catch (__) {}
        }

        return (
          '<pre><code class="hljs">' +
          md.utils.escapeHtml(str) +
          "</code></pre>"
        );
      },
    });
    md.use(mk).use(require("markdown-it-container"), "timestamp", {
      validate: function (params) {
        return params.trim().match(/^timestamp\s+([0-9]+:[0-9]+)(.*)$/);
      },

      render: function (tokens, idx) {
        // block匹配得到时间戳(::: timestamp xx:xx :::)
        let m = tokens[idx].info
          .trim()
          .match(/^timestamp\s+([0-9]+:[0-9]+)(.*)$/);

        if (tokens[idx].nesting === 1) {
          const [minute, second] = m[1].split(":");
          noteTimeStampArr.push(parseInt(minute) * 60 + parseInt(second));
          // opening tag
          return (
            '<div class="Timestamp-container" ondblclick="timeStampBlockClick(this)">\n' +
            '<button class="Timestamp-timestamp">' +
            md.utils.escapeHtml(m[1]) +
            "</button>\n" +
            md.utils.escapeHtml(m[2]) +
            "\n"
          );
        } else {
          // closing tag
          return "</div>\n";
        }
      },
    });
    // 将 Markdown 内容解析为 HTML
    setHTMLContent(md.render(content));
  }, [content]);
  useEffect(() => {
    noteTimeStampElems = containerRef.current.getElementsByClassName(
      "Timestamp-container",
    );
    if (noteTimeStampElems.length !== 0) {
      let i;
      for (i = 1; i < noteTimeStampArr.length; i++) {
        if (noteTimeStampArr[i] > videoTimeStamp) {
          break;
        }
      }
      let highlightedElems = containerRef.current.getElementsByClassName(
        "Timestamp-highlighted",
      );
      for (const highlightedElem of highlightedElems) {
        highlightedElem.className = "Timestamp-container";
      }
      let lastNoteTimeStampElem = noteTimeStampElems[i - 1];
      lastNoteTimeStampElem.className =
        lastNoteTimeStampElem.className + " Timestamp-highlighted";
      animateScrollTo(
        containerRef.current,
        lastNoteTimeStampElem.offsetTop - containerRef.current.offsetHeight / 2,
        500,
      );
    }
  }, [containerRef, videoTimeStamp]);
  // 使用 dangerouslySetInnerHTML 将 HTML 内容注入到组件中
  return <div dangerouslySetInnerHTML={{ __html: HTMLContent }} />;
};
export default MarkdownViewer;
